import subprocess
import argparse

import apscheduler.job
import consul
from apscheduler.schedulers.blocking import BlockingScheduler
def set_interval(args,sync_job):
    try:
        value = args.consul.kv.get("settings/interval")
        interval=int(value[1]['Value'])
        if interval>0 and interval!=args.interval:
            args.interval=interval
            sync_job.reschedule("interval",seconds=interval)
            print("change interval to {0}".format(interval))
    except Exception as e:
        pass

def sync_repo(args):
    # subprocess.call("rclone copy {0}:/ {1} --create-empty-src-dirs -P --exclude {2}".format(args.remote_repo,args.local_repo,"\"*.jpg\""),shell=True)
    subprocess.call("rclone sync {0}:/ {1} --create-empty-src-dirs -P".format(args.remote_repo,args.local_repo),shell=True)

if __name__=="__main__":
    arg_parser = argparse.ArgumentParser()
    arg_parser.add_argument("remote_repo",type=str)
    arg_parser.add_argument("local_repo",type=str)
    arg_parser.add_argument("--interval",type=int,default=30)
    arg_parser.add_argument("--consul_host", type=str, default=None)
    arg_parser.add_argument("--consul_port", type=int, default=0)
    args=arg_parser.parse_args()
    args.consul=None
    if args.consul_host is not None:
        try:
            args.consul = consul.Consul(args.consul_host,args.consul_port)
        except Exception as e:
            print(e)
            args.consul=None

    sync_repo(args)# run once at first
    sched = BlockingScheduler()
    sync_job = sched.add_job(sync_repo,'interval',args=(args,),id='sync_repo',seconds=args.interval)
    if args.consul is not None:
        sched.add_job(set_interval,'interval',args=(args,sync_job),id="set_time",seconds=10)
    sched.start()


